<template>
  <el-dialog v-model="visible"
             type="border-card"
             header-class="border-b"
             body-class="px-0 pt-4"
             footer-class="border-t"
             fullscreen>
    <template #header="{ close, titleId, titleClass }">
      <el-page-header @back="visible=false">
        <template #content>
          <span class="text-large font-600 mr-3"> 流程设计器 </span>
        </template>
      </el-page-header>
    </template>
    <div class="flex absolute right-0 z-50" style="transform: translateY(4px) translateX(-22px)">
      <el-select style="margin-right: 12px; width: 200px" placeholder="请选择版本">
        <el-option v-for="item in []"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value">
          <div style="display: flex;justify-content: space-between;align-items: center">
            {{ item.label }}
            <el-tag size="mini" type="info">未发布</el-tag>
          </div>
        </el-option>
      </el-select>
      <el-button :disabled="workFlowData.definitionStatus === 'Yes'" @click="doSave">保存</el-button>
      <el-button :disabled="workFlowData.definitionStatus === 'Yes'" type="primary" @click="doPublish">发布</el-button>
    </div>
    <el-tabs model-value="设计器"
             type="border-card"
             class="h-full">
      <el-tab-pane label="设计器" name="设计器">
        <div id="bpms-canvas" class="" style="height: calc(100vh - 130px)"></div>
        <div class="absolute bg-white w-96 shadow-l px-2" style="top:1px; right:1px;z-index: 110; height: calc(100vh - 132px)">
          <workflow-editor-child1 v-model="workFlowData"/>
        </div>
      </el-tab-pane>
      <el-tab-pane label="XML" name="XML">
        <epms2-ace-editor v-model="workFlowData.original.data"
                          lang="xml"
                          @update:modelValue="onAceEditorChange"
                          style="height: calc(100vh - 130px);"/>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
  <workflow-editor-child-bpmn-start-event ref="bpmnStartEventDrawerRef"/>
  <workflow-editor-child-bpmn-task ref="bpmnTaskDrawerRef"/>
  <workflow-editor-child-bpmn-sequence-flow-drawer ref="bpmnSequenceFlowDrawerRef"/>
  <workflow-editor-child-bpmn-end-event ref="bpmnEndEventDrawerRef"/>
<!--  <workflow-editor-child-bpmn-intermediate-throw-event ref="bpmnIntermediateThrowEventDrawerRef"/>-->
</template>

<script setup>
/////////////////////////////////   外部依赖导入    //////////////////////////
import {onMounted, onUnmounted, ref, reactive, nextTick, onBeforeUnmount} from 'vue'
import {useRouter} from 'vue-router';
import defaultLogo from "@/assets/images/default-logo.png";
import defaultAvatar from "@/assets/images/default-avatar.jpg";
import {$localStorage} from "@/utils/application-storage.js";
import $apiService from "@/axios/api.js";

import BpmnModeler from 'bpmn-js/lib/Modeler';
import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas';
import ZoomScrollModule from 'diagram-js/lib/navigation/zoomscroll';
import BpmnColorPickerModule from 'bpmn-js-color-picker';
import PaletteModule from 'bpmn-js/lib/features/palette';
import ModelingModule from 'bpmn-js/lib/features/modeling';
import "bpmn-js/dist/assets/diagram-js.css"
import "bpmn-js/dist/assets/bpmn-font/css/bpmn.css"
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css"
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css"
import DefaultEmptyXML from "@/components/bpmn/defaultEmptyXML.js";
import Epms2AceEditor from "@/components/epms2-ace-editor.vue";
import WorkflowEditorChild1 from "@/views/WorkflowMnt/component/WorkflowEditorChild1.vue";
import WorkflowEditorChildBpmnStartEvent from "@/views/WorkflowMnt/component/WorkflowEditorChildBpmnStartEvent.vue";
import WorkflowEditorChildBpmnTask from "@/views/WorkflowMnt/component/WorkflowEditorChildBpmnTask.vue";
import WorkflowEditorChildBpmnEndEvent from "@/views/WorkflowMnt/component/WorkflowEditorChildBpmnEndEvent.vue";
import WorkflowEditorChildBpmnSequenceFlowDrawer from "@/views/WorkflowMnt/component/WorkflowEditorChildBpmnSequenceFlowDrawer.vue";


/////////////////////////////////   私有变量定义    //////////////////////////
const $router = useRouter();
const visible = ref(false);
const tenantInfo = ref({
  id: "",
  logo: defaultLogo,
  tenantCode: '',
  systemName: ''
})
const myProfile = ref({
  avatarUrl: defaultAvatar,
  realName: ''
})
const workFlowData = ref({
  original: {
    data: DefaultEmptyXML()
  }
})
let bpmnModelerInstance = null

const bpmnStartEventDrawerRef = ref({show: ()=>{}});
const bpmnSequenceFlowDrawerRef = ref({show: ()=>{}});
const bpmnTaskDrawerRef = ref({show: ()=>{}});
const bpmnEndEventDrawerRef = ref({show: ()=>{}});
const bpmnIntermediateThrowEventDrawerRef = ref({show: ()=>{}});

/////////////////////////////////   生命周期方法 //////////////////////////
onMounted(() => {
  tenantInfo.value = $localStorage.getTenantInfo()
  myProfile.value = $localStorage.getMyProfile()
});
onBeforeUnmount(() => {
  if (bpmnModelerInstance) {
    bpmnModelerInstance.destroy()
    bpmnModelerInstance = null
  }
})
onUnmounted(() => {
});
/////////////////////////////////   页面方法    //////////////////////////
const show = async (data) => {
  visible.value = true
  if (data) workFlowData.value = data
  await nextTick();
  initBpmnModeler()
}

const initBpmnModeler = () => {
  bpmnModelerInstance = new BpmnModeler({
    container: '#bpms-canvas',
    additionalModules: [
      BpmnColorPickerModule,
      PaletteModule,
      ModelingModule,
      MoveCanvasModule,
      ZoomScrollModule
    ],
    moddleExtensions: {},
  });
  // 初始化空白流程
  bpmnModelerInstance.importXML(workFlowData.value.original.data)
  const eventBus = bpmnModelerInstance.get('eventBus');
  eventBus.on('import.parse.complete', function (event) {
    if (!event.error) {
      console.log('BPMN 模型解析成功');
    } else {
      console.error('BPMN 模型解析失败:', event.error);
    }
  });
  eventBus.on('element.click', function (event) {
    const element = event.element;
    console.log('点击了元素:', element.id);

    if (element.type === 'bpmn:StartEvent') {
      bpmnStartEventDrawerRef.value.show(element, {})
    }
    if (element.type === 'bpmn:Task') {
      bpmnTaskDrawerRef.value.show(element, {})
    }
    if (element.type === 'bpmn:SequenceFlow') {
      bpmnSequenceFlowDrawerRef.value.show(element, {})
    }
    if (element.type === 'bpmn:IntermediateThrowEvent') {
      // bpmnIntermediateThrowEventDrawerRef.value.show(element, {})
    }
    if (element.type === 'bpmn:EndEvent') {
      bpmnEndEventDrawerRef.value.show(element, {})
    }
    // if (element.type === 'bpmn:SequenceFlow') {
    //   bpmnStartEventDrawerRef.show()
    // }
    // if (element.type === 'bpmn:ExclusiveGateway') {
    //   bpmnStartEventDrawerRef.show()
    // }
    // if (element.type === 'bpmn:ParallelGateway') {
    //   bpmnStartEventDrawerRef.show()
    // }
    // businessObject.name;
  });
  eventBus.on('element.changed', function (event) {
    const element = event.element;
    console.log('任务元素发生了变化，元素 ID:', element.id)
    // if (element.type === 'bpmn:Task') {
    //   console.log('任务元素发生了变化，元素 ID:', element.id);
    // }
    bpmnModelerInstance.saveXML({format: true}).then(({xml}) => {
      workFlowData.value.original.data = xml
    })
  });
}
const onAceEditorChange = (content) => {
  bpmnModelerInstance.importXML(content)
}
const doSave = () => {
}
const doPublish = () => {
}
const ddd = () => {
}
const eeee = () => {
}
/////////////////////////////////   暴露内部方法，让父组件可以访问    //////////////////////////
defineExpose({
  show
});
</script>

<style scoped>

:deep(.el-tabs__content) {
  padding: 0;
}
</style>
